import { observer } from 'mobx-react-lite';
import Navbar from '@/components/Navbar';
import { View } from '@tarojs/components';
import systemStore from '@/stores/SystemStore';
import './index.less';
import ImageComp from '@/components/Image';
import { useEffect, useState } from 'react';
import AuthConstant from '@/constant/AuthConstant';
import BusinessConstant from '@/constant/BusinessConstant';
import chatStore from '@/stores/ChatStore';
import EmptyComp from '@/components/Empty';
import { ChatEntity } from '@/entities/ChatEntity';
import useIdentity from '@/hooks/useIdentity';
import { TenantEntity } from '@/entities/TenantEntity';
import { LandlordEntity } from '@/entities/LandlordEntity';
import { navigateTo, showToast } from '@tarojs/taro';
import { CommonUtil } from '@/utils/CommonUtil';
import ChatBusiness from '@/business/ChatBusiness';
import useChat from '@/hooks/useChat';

function ChatSession() {
  const {
    setChatReceiver,
    chatSessionList,
    setChatSessionList,
    setChatReceiverInfo,
    chatReceiverInfo,
    senderId,
    chatSessionLastOneMessageList,
  } = chatStore;
  const { getUserByIdList } = useIdentity();
  const { useLeaveChatSession } = useChat();
  const [longPressVisible, setLongPressVisible] = useState(false);
  const [currentReceiverId, setCurrentReceiverId] = useState('');
  const [menuX, setMenuX] = useState(0);
  const [menuY, setMenuY] = useState(0);
  /**
   * 删除 session
   */
  const delSession = async () => {
    await ChatBusiness.delChatSession(senderId, currentReceiverId);
    // 删除 chatStore 的当前session
    setChatSessionList([
      ...chatSessionList.filter((session: ChatEntity.IChatSession) => {
        return session.receiverId !== currentReceiverId;
      }),
    ]);
    showToast({
      title: '删除成功',
      icon: 'success',
    });
  };

  /**
   * 长按的菜单
   */
  const longPressMenu = [
    {
      title: '删除',
      handleClick: delSession,
    },
  ];
  /**
   * 获取对方的信息
   */
  const getOtherInfo = async () => {
    if (senderId && chatSessionList) {
      const otherList = chatSessionList?.map(
        (session: ChatEntity.IChatSession) => {
          // 获取对方id
          const otherId =
            session.senderId === senderId
              ? session.receiverId
              : session.senderId;
          // 判断身份
          const [identity, id] = otherId.split(',');
          return {
            otherId,
            identity:
              identity === BusinessConstant.SIGN_LANDLORD
                ? AuthConstant.LANDLORD
                : AuthConstant.TENANT,
            id: Number(id),
          };
        }
      );
      // 获取otherList里面的信息
      const otherUserList: any = await getUserByIdList(otherList);
      setChatReceiverInfo(otherUserList);
    }
  };

  useLeaveChatSession();

  useEffect(() => {
    getOtherInfo();
  }, [chatSessionList]);

  /**
   * 去聊天
   * @param receiver
   */
  const toChatMessage = (
    receiver:
      | TenantEntity.IChatSessionTenant
      | LandlordEntity.IChatSessionLandlord
  ) => {
    setChatReceiver(receiver);
    navigateTo({
      url: `/pages/chatMessage/index?name=${receiver?.name}&tenantId=${receiver?.id}`,
    });
  };

  /**
   * 长按
   */
  const handleLongPress = (event: any, receiverId: string) => {
    setLongPressVisible(true);
    setCurrentReceiverId(receiverId);
    const { x, y } = event.detail;
    setMenuX(x);
    setMenuY(y);
  };

  return (
    <Navbar title='消息中心' mode='home' bgColor='var(--mini-first)'>
      <View
        className='chat-session-container'
        style={{ height: systemStore.haveNavbarNotTabbarHeight }}
        onClick={() => setLongPressVisible(false)}
      >
        {chatSessionList?.length ? (
          chatSessionList?.map((chatSession: ChatEntity.IChatSession) => {
            let receiver:
              | TenantEntity.IChatSessionTenant
              | LandlordEntity.IChatSessionLandlord;
            if (chatSession.senderId === senderId) {
              receiver = chatReceiverInfo?.find(
                (c) => c.otherId == chatSession.receiverId
              );
            } else {
              receiver = chatReceiverInfo?.find(
                (c) => c.otherId == chatSession.senderId
              );
            }
            const lastMessage: ChatEntity.IChatMessage =
              chatSessionLastOneMessageList?.find(
                (c: ChatEntity.IChatMessage) => {
                  const { senderId, receiverId } = chatSession;
                  return (
                    (c.senderId === senderId && c.receiverId === receiverId) ||
                    (c.senderId === receiverId && c.receiverId === senderId)
                  );
                }
              );
            return (
              <View
                key={chatSession.id}
                className='session-wrap'
                onClick={() => toChatMessage(receiver)}
                onLongPress={(event) =>
                  handleLongPress(event, chatSession.receiverId)
                }
              >
                <View className='head-img-wrap'>
                  <ImageComp
                    className='other-head-img'
                    src={receiver?.headImg}
                  />
                  {chatSession.unread ? (
                    <View className='drop'>{chatSession.unread}</View>
                  ) : null}
                </View>
                <View className='session-message'>
                  <View className='flex justify-between items-center'>
                    <View className='other-name'>{receiver?.name}</View>
                    <View className='date'>
                      {CommonUtil.formatChatDate(lastMessage?.updatedAt, true)}
                    </View>
                  </View>
                  <View className='message'>
                    {lastMessage.type === BusinessConstant.CHAT_TYPE_TEXT
                      ? lastMessage?.content
                      : lastMessage.type === BusinessConstant.CHAT_TYPE_IMAGE
                      ? '[图片]'
                      : '[视频]'}
                  </View>
                </View>
              </View>
            );
          })
        ) : (
          <EmptyComp text='暂无消息' />
        )}
        {longPressVisible ? (
          <View className='long-press-menu' style={{ left: menuX, top: menuY }}>
            {longPressMenu.map((item) => {
              return (
                <View className='menu-item' onClick={item.handleClick}>
                  {item.title}
                </View>
              );
            })}
          </View>
        ) : null}
      </View>
    </Navbar>
  );
}

export default observer(ChatSession);
